package com.party.jackclientandroid;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;

import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.HomeService;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.Notice;
import com.party.jackclientandroid.controller.DialogController;
import com.party.jackclientandroid.ui_home.fragment.HomeFragment;
import com.party.jackclientandroid.ui_home.fragment.ShareFragment;
import com.party.jackclientandroid.ui_home.fragment.SpellingGroupFragment;
import com.party.jackclientandroid.ui_mine.MineFragment;
import com.party.jackclientandroid.ui_order.OrderFragment;
import com.party.jackclientandroid.view.dialog.HomeNewGuideDialog;
import com.party.jackclientandroid.view.dialog.NoticeDialog;
import com.yinglan.alphatabs.AlphaTabView;
import com.yinglan.alphatabs.AlphaTabsIndicator;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 首页
 */
public class MainActivity extends BaseActivity {

    @BindView(R.id.bottom_bar)
    AlphaTabsIndicator mTabLayout;
    @BindView(R.id.bottom_ll)
    LinearLayout bottomLl;
    private List<Fragment> fragmentList = new ArrayList<>();
    private HomeFragment homeFragment;
    private SpellingGroupFragment spellingGroupFragment;
    private ShareFragment shareFragment;
    private OrderFragment orderFragment;
    private MineFragment mineFragment;
    private BaseFragment currentFragment;
    private HomeService homeService;
    private int currentTag = 0;
    long firstTime;


    /**
     * 视频所在的tab index
     */
    private int videoIndex = 2;
    private int mChooseTabNum;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        requestNotice();
    }

    private void requestNotice() {
        addDisposableIoMain(homeService.getNotice(), new DefaultConsumer<Notice>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<Notice> result) {
                if (result.getData() != null) {
                    Notice notice = result.getData();
                    if (result.getData().equals("")) {
                    } else {
                        NoticeDialog ad = DialogController.showNoticeDialog(mActivity, notice);
                        ad.show();
//                        mApplication.getImageLoaderFactory().loadCommonImgByUrl(mActivity, img, ad.getImg());
                    }
                }
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        currentFragment.onMyReStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mChooseTabNum == 2) {
            try {
                shareFragment.onHiddenChanged(false);
            } catch (Exception e) {
            }
        }
    }

    protected void initData() {
        homeService = new HomeService(this);
        homeFragment = HomeFragment.newInstance();
        spellingGroupFragment = SpellingGroupFragment.newInstance();
        shareFragment = ShareFragment.newInstance();
        orderFragment = OrderFragment.newInstance();
        mineFragment = MineFragment.newInstance();

        fragmentList.add(homeFragment);
        fragmentList.add(spellingGroupFragment);
        fragmentList.add(shareFragment);
        fragmentList.add(orderFragment);
        fragmentList.add(mineFragment);


        mTabLayout.setOnTabChangedListner((int tabNum) -> {
            if (tabNum == 2 || tabNum == 3 || tabNum == 4) {
                if (TextUtils.isEmpty(mApplication.getToken())) {
                    handleNeedLogin();
                    mTabLayout.setTabCurrenItem(currentTag);
                    return;
                }
            }
            switchFragment(fragmentList.get(tabNum));
            chooseTab(tabNum);
            mChooseTabNum = tabNum;
            currentTag = tabNum;
        });
        mTabLayout.setTabCurrenItem(0);

//        if (mApplication.getToken() != null) {
//            mTabLayout.setTabCurrenItem(2);
//            mTabLayout.setTabCurrenItem(0);
//        } else {
//            mTabLayout.setTabCurrenItem(0);
//        }

        //0 为 未认证用户 //取消红包暂时 注销掉改代码
//        String isRegister = getIntent().getStringExtra("isRegister");
//        if (isRegister != null) {
//            pullRealAuth();
//        }
    }

    /**
     * 设置底部菜单栏的新消息
     *
     * @param videoSize
     */
    public void setUpdateTab(int videoSize) {
        mTabLayout.getTabView(2).showNumber(videoSize);
    }

    private void switchFragment(Fragment targetFragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment fragmentByTag = getSupportFragmentManager().findFragmentByTag(targetFragment.getClass().getSimpleName());
        if (fragmentByTag == null) {
            transaction.add(R.id.fragment_layout, targetFragment, targetFragment.getClass().getSimpleName());
        }
        if (currentFragment != targetFragment && currentFragment != null) {
            transaction.hide(currentFragment);
        }
        transaction.show(targetFragment);
        transaction.commit();
        currentFragment = (BaseFragment) targetFragment;
    }


    @Override
    public void onPause() {
        super.onPause();
        if (mChooseTabNum == 2) {
            try {
                shareFragment.onHiddenChanged(true);
            } catch (Exception e) {
            }
        }
    }

    /**
     * 获取当前显示的tabNum
     *
     * @return
     */
    public int getChooseTabNum() {
        return mChooseTabNum;
    }

    Field mTextColorSelected = null;

    /**
     * 选中tab
     *
     * @param tabNum
     */
    private void chooseTab(int tabNum) {
        AlphaTabView videoItemView = mTabLayout.getTabView(2);
        if (mTextColorSelected == null) {
            try {
                mTextColorSelected = videoItemView.getClass().getDeclaredField("mTextColorSelected");
                mTextColorSelected.setAccessible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (tabNum == videoIndex) {
            try {
                mTextColorSelected.setInt(videoItemView, getResources().getColor(R.color.colorMain));
                videoItemView.setIconAlpha(1f);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mTabLayout.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.color_c7333333));
        } else {
            try {
                mTextColorSelected.setInt(videoItemView, 0xFF000000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mTabLayout.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.color_f6f6f6));
        }
    }

    private void handleNeedLogin() {
        mApplication.finishOtherActivity(this);
        mApplication.cleanUser();
        Intent intent = new Intent(mActivity, LoginActivity.class);
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000L) {
            showToast("再按一次退出程序");
            firstTime = secondTime;
            return;
        }
        super.onBackPressed();
    }

    public AlphaTabsIndicator getmTabLayout() {
        return mTabLayout;
    }


    public void pullRealAuth() {
        HomeNewGuideDialog alertDialog = new HomeNewGuideDialog.Builder(mActivity)
                .setAliAuth((View v) -> {
                    ((AlertDialog) v.getTag()).dismiss();

                    //跳转到 认证 现在已经取消了
//                    AliAuthController aliAuth = new AliAuthController(mActivity);
//                    aliAuth.auth((String auth_code) -> {
//                        showLoadingDialog();
//                        aliAuth.bindingZfbUser(auth_code, (BindingInfo bindingInfo) -> {
//                            hideAlertDialog();
//                            User user = mApplication.getUser();
//                            user.setIsBindingAli(1);//绑定成功
//                            mApplication.setUser(user);
//                            startActivity(MyWalletActivity.class);
//                        });
//                    });
                }).create();
        alertDialog.setCancelable(false);
        Window window = alertDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        alertDialog.show();
    }

}
